package {
	import flash.display.DisplayObject;
	import flash.display.MovieClip;
	import flash.display.StageAlign;
	import flash.display.StageScaleMode;
	import flash.events.Event;
	import flash.events.IOErrorEvent;
	import flash.events.ProgressEvent;
	import flash.utils.getDefinitionByName;
	import libT.FillBar;
	
	/**
	 * Preloader class for the game
	 * @author everyone
	 */
	public class Preloader extends MovieClip {
		
		private var loader:FillBar;
		
		/**
		 * Creates a typical rectangular preloader (Temporary?)
		 */
		public function Preloader() {
			if (stage) {
				stage.scaleMode = StageScaleMode.NO_SCALE;
				stage.align = StageAlign.TOP_LEFT;
			}
			addEventListener(Event.ENTER_FRAME, checkFrame);
			loaderInfo.addEventListener(ProgressEvent.PROGRESS, progress);
			loaderInfo.addEventListener(IOErrorEvent.IO_ERROR, ioError);
			
			//create a new FillBar with given params
			loader = new FillBar(100, 10, 0xFF0000, 0x00FFFF);
			addChild(loader);
			
			//set it to the middle of the stage if possible
			if (stage) {
				loader.x = stage.stageWidth / 2 - 50;
				loader.y = stage.stageHeight / 2 - 5;
			}
		}
		
		private function ioError(e:IOErrorEvent):void {
			trace(e.text);
		}
		
		private function progress(e:ProgressEvent):void {
			//set the fill bar's fill to the fraction of bytes loaded
			loader.setFill(e.bytesLoaded / e.bytesTotal);
		}
		
		private function checkFrame(e:Event):void {
			if (currentFrame == totalFrames) {
				stop();
				loadingFinished();
			}
		}
		
		private function loadingFinished():void {
			removeEventListener(Event.ENTER_FRAME, checkFrame);
			loaderInfo.removeEventListener(ProgressEvent.PROGRESS, progress);
			loaderInfo.removeEventListener(IOErrorEvent.IO_ERROR, ioError);
			
			//remove the fill bar
			removeChild(loader);
			
			startup();
		}
		
		private function startup():void {
			var mainClass:Class = getDefinitionByName("Main") as Class;
			addChild(new mainClass() as DisplayObject);
		}
		
	}
	
}